<template>
  <Catogary
    :catagaryOneData="catagaryOneData"
    :catagaryTwoData="catagaryTwoData"
    :catagaryThreeData="catagaryThreeData"
    :disabled="toggle"
    @getCategary="handleGet"
  ></Catogary>
  <template v-if="!toggle">
    <ElCard>
      <ElButton
        type="primary"
        size="small"
        icon="Plus"
        style="margin-bottom: 10px"
        :disabled="!tag"
        @click="handleAddAttr"
      >
        添加属性
      </ElButton>
      <ElTable border :data="attrList">
        <ElTableColumn
          label="序号"
          type="index"
          align="center"
          width="150px"
        ></ElTableColumn>
        <ElTableColumn
          label="属性名称"
          width="150px"
          prop="attrName"
        ></ElTableColumn>
        <ElTableColumn label="属性值名称">
          <template #default="{ row }">
            <el-tag
              style="margin: 5px"
              type="success"
              v-for="ele in row.attrValueList"
              :key="ele.id"
            >
              {{ ele.valueName }}
            </el-tag>
          </template>
        </ElTableColumn>
        <ElTableColumn label="操作" width="150px">
          <template #default="{ row }">
            <ElButton
              type="primary"
              size="small"
              icon="Edit"
              @click="handleEdit(row)"
            ></ElButton>
            <el-popconfirm
              :title="`你确定要删除${row.attrName}?`"
              @confirm="handleDelAttr(row)"
              width="200px"
            >
              <template #reference>
                <ElButton type="danger" size="small" icon="Delete"></ElButton>
              </template>
            </el-popconfirm>
          </template>
        </ElTableColumn>
      </ElTable>
    </ElCard>
  </template>
  <template v-else>
    <ElCard>
      <ElForm>
        <ElFormItem label="属性名称">
          <ElInput
            placeholder="请输入你的属性名"
            style="width: 200px"
            size="small"
            v-model="attrData.attrName"
          ></ElInput>
        </ElFormItem>
      </ElForm>
      <ElButton
        type="primary"
        size="small"
        icon="Plus"
        :disabled="!attrData.attrName"
        @click="handleAddAttrValue"
      >
        添加属性
      </ElButton>
      <ElButton type="default" size="small" @click="handleCancel">
        取消
      </ElButton>
      <ElTable :data="attrData.attrValueList">
        <ElTableColumn
          label="序号"
          type="index"
          align="center"
          width="100px"
        ></ElTableColumn>
        <ElTableColumn label="属性值">
          <!-- row是attrValueList中的每个对象 -->
          <template #default="{ row, $index }">
            <ElInput
              placeholder="请输入你的属性值"
              v-model="row.valueName"
              v-if="!isShowDiv[$index]"
              @blur="handleBlur(row, $index)"
              :ref="
                (el) =>
                  setAttrValueInputRef(
                    el as InstanceType<typeof ElInput>,
                    $index,
                  )
              "
            ></ElInput>
            <div v-else @click="handleDivClick(row, $index)">
              {{ row.valueName }}
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn label="操作">
          <template #="{ row, $index }">
            <ElButton
              v-if="isShowDiv[$index]"
              type="danger"
              size="small"
              icon="Delete"
              @click="delRelateInpVal($index)"
            ></ElButton>
          </template>
        </ElTableColumn>
      </ElTable>
      <ElButton
        type="primary"
        size="small"
        @click="handleSave"
        :disabled="!saveable"
      >
        保存
      </ElButton>
      <ElButton type="default" size="small" @click="handleCancel">
        取消
      </ElButton>
    </ElCard>
  </template>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed, nextTick } from 'vue'
import type { categaryLevel, catagrayIDs } from '@/api/product/catagary/types'
import {
  ElCard,
  ElButton,
  ElTable,
  ElMessage,
  ElForm,
  ElFormItem,
  ElInput,
} from 'element-plus'
import Catogary from '@/components/Catagary/index.vue'
import {
  reqCatagaryOne,
  reqCatagaryTwo,
  reqCatagaryThree,
  reqAttrList,
  reqAddOrUpdateAttr,
  reqDelAttr,
} from '@/api/product/attr/index.ts'
import type {
  CatagaryResponseData,
  CatagaryResponseType,
  AttrType,
  AttrValueType,
} from '@/api/product/attr/types.ts'
//一级分类数据
const catagaryOneData = ref<CatagaryResponseData[]>([])
//二级分类数据
const catagaryTwoData = ref<CatagaryResponseData[]>([])
//三级分类数据
const catagaryThreeData = ref<CatagaryResponseData[]>([])
//属性数据
const attrList = ref<AttrType[]>([])
//当toggle为false时，不切换
const toggle = ref<boolean>(false)
//判断选择分类完的tag
const tag = ref<boolean>(false)
//存储是否展示div
const isShowDiv = ref<boolean[]>([])
//存储分类ID
const ids = ref<catagrayIDs>({
  c1Id: '',
  c2Id: '',
  c3Id: '',
})
//收集属性数据
const attrData: AttrType = reactive({
  attrName: '',
  categoryId: '',
  categoryLevel: 3,
  attrValueList: [],
})
//收集每个属性值输入框实例用于聚焦
const attrValueInputRefs = ref<Array<InstanceType<typeof ElInput> | null>>([])
//当前是否可以保存
const saveable = computed(() => {
  if (!attrData.attrName) return false
  if (attrData.attrValueList.length === 0) return false
  for (let i = 0; i < attrData.attrValueList.length; ++i) {
    if (attrData.attrValueList[i]?.valueName === '') return false
  }
  return true
})

const handleDelAttr = async (row: AttrType) => {
  try {
    const res: any = await reqDelAttr(row.id as number)
    if (res.code === 200) {
      ElMessage.success('删除属性成功')
      handleDisplayData(ids.value)
    } else {
      ElMessage.error('删除数据失败')
    }
  } catch (error) {
    console.log(error)
  }
}

//删除关于input框相关数据
const delRelateInpVal = ($index: number): void => {
  attrData.attrValueList.splice($index, 1)
  isShowDiv.value.splice($index, 1)
  attrValueInputRefs.value.splice($index, 1)
}

const setAttrValueInputRef = (
  el: InstanceType<typeof ElInput> | null,
  index: number,
) => {
  if (el) {
    attrValueInputRefs.value[index] = el
  }
}

const focusAttrValueInput = (index: number) => {
  nextTick(() => {
    attrValueInputRefs.value[index]?.focus()
  })
}
//处理DIV点击
const handleDivClick = (row: AttrValueType, $index: number) => {
  isShowDiv.value[$index] = false
  focusAttrValueInput($index)
}

//处理失去焦点的回调
const handleBlur = (row: AttrValueType, $index: number) => {
  if (row.valueName === '') {
    ElMessage.error('属性值不能为空')
    //删除该条相关数据
    delRelateInpVal($index)
  } else {
    //判断是否有重复属性值
    const res = attrData.attrValueList.find((ele) => {
      if (ele !== row) return ele.valueName === row.valueName
      return false
    })
    if (res) {
      ElMessage.error('重复的属性值')
      //删除该条相关数据
      delRelateInpVal($index)
    } else {
      isShowDiv.value[$index] = true
    }
  }
}
//处理保存按钮的回调
const handleSave = async () => {
  attrData.categoryId = ids.value.c3Id
  const res = await reqAddOrUpdateAttr(attrData)
  if (res.code === 200) {
    ElMessage.success(attrData.id ? '修改属性成功' : '添加属性成功')
    await handleDisplayData(ids.value)
    //返回页面
    toggle.value = !toggle.value
  } else {
    ElMessage.error(attrData.id ? '修改属性失败' : '新增属性失败')
  }
}

//处理添加属性的回调
const handleAddAttr = () => {
  toggle.value = true
  //初始化attrData,isShowDiv,attrValueInputRefs
  Object.assign(attrData, {
    attrName: '',
    categoryId: '',
    categoryLevel: 3,
    attrValueList: [],
  })
  isShowDiv.value = []
  attrValueInputRefs.value = []
}
//处理添加属性值的回调
const handleAddAttrValue = () => {
  attrData.attrValueList.push({
    valueName: '',
  })
  isShowDiv.value.push(false)
  focusAttrValueInput(attrData.attrValueList.length - 1)
}
//编辑按钮的回调
const handleEdit = (row: AttrType): void => {
  //这里要深拷贝
  Object.assign(attrData, JSON.parse(JSON.stringify(row)))
  toggle.value = true
}
//取消按钮的回调
const handleCancel = (): void => {
  toggle.value = !toggle.value
}

//处理选择分类
const handleGet = (obj: categaryLevel): void => {
  if (obj.level == 1) {
    //一级目录改变，获取二级类别
    attrList.value = []
    handleCatagaryTwo(obj.id as number)
  } else if (obj.level == 2) {
    //二级目录改变，获取三级目录
    attrList.value = []
    handleCatagaryThree(obj.id as number)
  } else if (obj.level == 3) {
    ids.value = obj.id as catagrayIDs
    handleDisplayData(obj.id as catagrayIDs)
  }
}
//分类选择完后展示数据
const handleDisplayData = async (ids: catagrayIDs) => {
  const res = await reqAttrList(ids)
  tag.value = true
  attrList.value = []
  if (res.code === 200) {
    if (res.data) {
      attrList.value = res.data
    }
  } else {
    ElMessage.error('获取属性出错')
  }
}

//处理分类数据
const handleCatagaryOne = async () => {
  const res: CatagaryResponseType = await reqCatagaryOne()
  tag.value = false
  if (res.code === 200) {
    catagaryOneData.value = res.data
  } else {
    ElMessage.error('获取一级分类失败')
  }
}
const handleCatagaryTwo = async (id: number) => {
  const res: CatagaryResponseType = await reqCatagaryTwo(id)
  tag.value = false
  if (res.code === 200) {
    catagaryTwoData.value = res.data
  } else {
    console.log(res)
    ElMessage.error('获取二级分类失败')
  }
}
const handleCatagaryThree = async (id: number) => {
  const res: CatagaryResponseType = await reqCatagaryThree(id)
  tag.value = false
  if (res.code === 200) {
    catagaryThreeData.value = res.data
  } else {
    console.log(res)
    ElMessage.error('获取三级分类失败')
  }
}
onMounted(() => {
  handleCatagaryOne()
})
</script>

<style scoped></style>
